package com.example.kotlinlearn.media

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.core.content.FileProvider
import com.example.kotlinlearn.BaseActivity
import com.example.kotlinlearn.databinding.ActivityMediaBinding
import java.io.File
import kotlin.concurrent.thread

class MediaActivity : BaseActivity() {

    private val takePhoto = 1
    lateinit var imageUrl:Uri
    lateinit var outputImage:File

    private val fromAlbum = 2

    private lateinit var binding: ActivityMediaBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMediaBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.button.setOnClickListener {
           takeImg()
        }
        binding.button1.setOnClickListener {
            //打开文件选择器
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            //指定只显示图片
            intent.type = "image/*"
            startActivityForResult(intent,fromAlbum)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            takePhoto->{
                //拍照成功就将图片显示在imageview中
                if (resultCode==Activity.RESULT_OK){
                    //将照片输出为bitmap
                    val bitmap = BitmapFactory.decodeStream(
                        contentResolver.openInputStream(imageUrl))
                    binding.imageView.setImageBitmap(rotateIfRequired(bitmap))
                }
            }
            fromAlbum->{
                if (resultCode==Activity.RESULT_OK&&data!=null){
                    data.data?.let { uri ->
                        //将选择的图片显示
                        val bitmap = getBitmapFromUrl(uri)
                        binding.imageView.setImageBitmap(bitmap)
                    }
                }
            }
        }
    }

    //根据图片url找到图片并返回bitmap
    private fun getBitmapFromUrl(uri: Uri) = contentResolver.openFileDescriptor(uri,"r")?.use{
        BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
    }

    //拍照
    private fun takeImg(){
        //创建File，储存照片,存在程序关联缓存目录里
        outputImage = File(externalCacheDir,"image.jpg")
        if (outputImage.exists()){
            outputImage.delete()
        }
        outputImage.createNewFile()
        //对于不同版本的android，选择获取图片地址方式不同，大于7.0的获取封装过后的Url，小于7.0的直接获取
        imageUrl = if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            FileProvider.getUriForFile(this,"com.example.kotlinlearn.fileprovider",outputImage)
        }else{
            Uri.fromFile(outputImage)
        }
        //启动相机程序
        val intent = Intent("android.media.action.IMAGE_CAPTURE")
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUrl)
        //隐式启动intent，找到能响应改intent的程序
        startActivityForResult(intent,takePhoto)
    }

    //对照片进行旋转处理
    private fun rotateIfRequired(bitmap: Bitmap):Bitmap{
        val exif = ExifInterface(outputImage.path)
        val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
        ExifInterface.ORIENTATION_NORMAL)
        return when(orientation){
            ExifInterface.ORIENTATION_ROTATE_90->rotateBitmap(bitmap,90)
            ExifInterface.ORIENTATION_ROTATE_180->rotateBitmap(bitmap,180)
            ExifInterface.ORIENTATION_ROTATE_270->rotateBitmap(bitmap,270)
            else->bitmap
        }
    }
    //照片旋转
    private fun rotateBitmap(bitmap: Bitmap,degree:Int):Bitmap{
        val matrix = Matrix()
        matrix.postRotate(degree.toFloat())
        val rotateBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.width,bitmap.height,matrix,true)
        bitmap.recycle()
        return rotateBitmap
    }
}